import TextUtil from './text';

const src = require('./../../assets/images/lollipop.png');

var OFFSETTOP = 44.13; // 图片旋转以后距离顶上上距离
var OFFSETBOTTOM = 82.19; // 图片旋转以后距离顶上上距离
var OFFSETLEFT = 50;  // 装订预留
var OFFSETRIGHT = 50;  // 右边留白
var PAGEWIDTH = 595.28; // 页面的宽度
const RATIO = 0.7070707070707071; // a4纸张的比例
const COL = 1;

// 定义一个变量 移动端字体大小，方便移动端预览页面做适配
var MOBILEFONTSIZE = '12px';

export default {
    /**
     * 判断一个dom在父节点中是否可见
     *
     * @param  {dom}  pageDiv [父节点]
     * @param  {dom}  itemDom [子节点]
     * @return {Boolean}         [description]
     */
    inviewport: function(itemDom, pageDiv) {
        return !this.belowthefold(itemDom, pageDiv) && !this.abovethetop(itemDom, pageDiv);
    },

    belowthefold: function(itemDom, pageDiv) {
        var fold;

        if (pageDiv === undefined || pageDiv === window) {
            fold = (window.innerHeight ? window.innerHeight : $(window).height()) + $(window).scrollTop();
        } else {
            fold = $(pageDiv).offset().top + $(pageDiv).height();
        }

        return fold <= $(itemDom).offset().top + $(itemDom).height();
    },

    abovethetop: function(itemDom, pageDiv) {
        var fold;

        if (pageDiv === undefined || pageDiv === window) {
            fold = $(window).scrollTop();
        } else {
            fold = $(pageDiv).offset().top;
        }
        return fold >= $(itemDom).offset().top  + $(itemDom).height();
    },

    randerAlignFont: function(menuDom, settings) {
        var _this = this;
        $.each(menuDom,function(index,item){
            if (settings) {
                if (settings.catalog_align) {
                    _this.changeCatalogAlign(item, settings.catalog_align);
                } else {
                    _this.changeCatalogAlign(item, 'center');
                }
                if (settings.catalog_font) {
                    _this.changeFont(item, settings.catalog_font);
                } else {
                    _this.changeFont(item, '黑体');
                }
            } else {
                _this.changeCatalogAlign(item, 'center');
                _this.changeFont(item, '黑体');
            }
        });
    },

    renderFooterPage: function ($allPages, settings) {
        // 如果页脚和页码有配置，则根据配置渲染，否则默认渲染页脚和页码
        if (!settings) {
            settings = {
                show_footer: 1,
                show_pageno: 1,
            };
        } else {
            if (settings.show_footer) {
                $allPages.removeClass('no-footer');
            } else {
                if (settings.show_footer === 0) {
                    $allPages.addClass('no-footer');
                }
            }
            if (settings.show_pageno) {
                $allPages.removeClass('no-page');
            } else {
                if (settings.show_pageno === 0) {
                    $allPages.addClass('no-page');
                }
            }
        }
    },

    renderPrintStyle: function ($allPages, settings) {
        if (!settings) {
            settings = {
                double_print: 1,
            };
        } else {
            if (settings.double_print) {
                $allPages.each(function(index, el) {
                    if (index % 2 !== 0) {
                        $(el).addClass('double-print left-align');
                    } else {
                        $(el).addClass('double-print');
                    }
                });
            }
        }
    },

    /**
     * 改变目录的对齐方式
     * @param  {string} type [对齐方式]
     *
     */
    changeCatalogAlign: function(menuDom, type) {
        var $catalog = $(menuDom).find('.catalog');
        $catalog.css({'text-align': type});
    },

    /**
     * 改变字体
     * @param  {string} font [字体系列]
     */
    changeFont: function(menuDom, font) {
        if (font === '宋体') {
            $(menuDom).css({'font-family':'Songti SC,"宋体",serif'});
        } else {
            $(menuDom).css({'font-family':'Heiti SC,"微软雅黑","华文细黑",Droid Sans Fallback,sans-serif'});
        }
    },

    /**
     * 把宽度超过长度的图片 旋转90度 transform: rotate(-90deg);
     * @param  {[obj]} data 图片数据
     * @param  {[dom]} dom  页面的dom节点
     * @return {[dom]} dom  扭正以后 页面dom
     */
    correctImg: function (data, dom) {
        // 图片的预览页面，修改上下左右的padding
        OFFSETLEFT = 5;
        OFFSETRIGHT = 5;
        OFFSETTOP = 5;
        OFFSETBOTTOM = 5;
        // 目前的页面宽度是  595 * 841.89
        if (data.width && data.height) {
            let width = parseInt(data.width, 10) ;
            let height = parseInt(data.height, 10);
            let ratio = width/height;

            var contentWidth = PAGEWIDTH - OFFSETLEFT - OFFSETRIGHT;
            var contentHeight = PAGEWIDTH/RATIO - OFFSETTOP - OFFSETBOTTOM;
            let finalHeight, finalWidth;

            var moveRight = 0;
            if (width < height) {
                finalWidth = contentWidth;
                finalHeight = finalWidth/ratio;
                // 如果长边:短边 < A4 29:21 尽量撑满短边，顶格显示
                if (height / width < 29 / 21) {

                // 如果长边:短边 > A4 29:21 尽量撑满长边，居中显示
                } else {
                    finalHeight = contentHeight;
                    finalWidth =  contentHeight * ratio;
                    if (finalWidth > contentWidth) {
                        finalWidth = contentWidth;
                        finalHeight = finalWidth/ratio;
                    } else {
                        moveRight = (contentWidth - finalWidth)/2;
                    }
                }

                $(dom).find('.content img').css({
                    'width': finalWidth,
                    'height': finalHeight,
                    'margin-left': moveRight
                });

                return dom;
            } else {

                // 先计算旋转以后的图片的宽高
                finalHeight  = contentWidth;
                finalWidth = ratio * contentWidth;

                // 如果长边:短边 < A4 29:21 尽量撑满短边，顶格显示
                if (width / height < 29 / 21) {

                // 如果长边:短边 > A4 29:21 尽量撑满长边，居中显示
                } else {
                    finalWidth = contentHeight;
                    finalHeight =  contentHeight / ratio;
                    moveRight = (contentWidth - finalHeight)/2;
                }

                $(dom).find('.content img').css({
                    'width': finalWidth,
                    'height': finalHeight,
                    'position': 'absolute',
                    'left': '5px',
                    'margin-left': moveRight,
                    'top': (finalWidth + OFFSETTOP),
                    '-webkit-transform': 'rotate(-90deg)',
                    '-moz-transform': 'rotate(-90deg)',
                    '-ms-transform': 'rotate(-90deg)',
                    '-o-transform': 'rotate(-90deg)',
                    'transform': 'rotate(-90deg)',
                    '-webkit-transform-origin': '0 0',
                    '-moz-transform-origin': '0 0',
                    '-ms-transform-origin': '0 0',
                    '-o-transform-origin': '0 0',
                    'transform-origin': '0 0',
                });

                return dom;
            }
        }

        return dom;
    },

    /**
     * 根据电子书数据生成每个页面的dom
     *
     * @param  {array} list [电子书数据]
     * @param  {array} theme [电子书封面数据]
     * @param  {object} settings [材料的相关配置]
     *
     * @return {array}      [dom, dom, dom]
     */
    getPages: function(list, theme, settings) {
        var that = this;
        var allPages = [];
        let OFFSETLEFT = 10;

        // 目录页面

        // 生成隐藏的目录页面 渲染计算高度
        var menuPage = this.createPageDom(null, 'menuPage', 'render');

        // 创建隐藏的页面计算 目录
        $('body').append($('<div id="hideArea"></div>'));
        $('#hideArea').append(menuPage);

        // 目录列表容器
        var $menuPageContent =  $(menuPage).find('.content');

        // 对目录做特殊的处理
        if ($menuPageContent.closest('.page').hasClass('menu')) {
            OFFSETLEFT = $('.page.menu').css('padding-left');
        }

        var contentWidth = (PAGEWIDTH - OFFSETLEFT)/COL;
        var contentHeight = PAGEWIDTH/RATIO;
        $menuPageContent.css({'width': contentWidth , 'height': contentHeight});

        // 每个页面
        var page = null;
        var _this = this;

        // 菜单的文件标题的单个dom
        if (typeof list === 'string'){
            list = JSON.parse(list);
        }

        $menuPageContent.append(_this.createMenuDom( null, '目录', null, 'catalog', null, null));
        $(list).each(function(i, model) {
            window.fTitleOrder = -1;
            /**
             * 生成页面，数据放入，样式布局
             */

            if (!model.alt_mod_title) {
                model.alt_mod_title = model.mod_title;
            }
            var model_title = model.alt_mod_title;

            if (theme) {
                var modelTitlePage = _this.createPageDom(model_title, 'modelTitle', 'render');
            } else {
                var modelTitlePage = _this.createPageDom(model_title, 'modelTitle', null);
            }

            // 页面要放在目录计算之后push
            allPages.push(modelTitlePage);
            // 目录页：中的大标题(模块标题，例如，论文)
            var $modelTitleDiv = _this.createMenuDom( null, model_title, allPages.length, 'm-title', model.mod_db_table, i);
            $menuPageContent.append($modelTitleDiv);

            if (settings && settings.double_print) {
                // 大的模块名称要单独一页打，在后面插入空白页，页码要变化
                var blankPage = $('<div>', {'class': 'blank-page page'}).get(0);
                allPages.push(blankPage);
            }

            // 在页面中已经不可见,得放入下一个页面
            if (!that.inviewport($modelTitleDiv.get(0), $menuPageContent)) {
                menuPage  = _this.createPageDom(null, 'menuPage', 'render');
                $('#hideArea').append(menuPage);

                $menuPageContent =  $(menuPage).find('.content');
                $menuPageContent.css({'width': contentWidth , 'height': contentHeight});
                $menuPageContent.append($modelTitleDiv);
            }

            // 所有子集
            var dataset = model._form_table.dataset;
            var model = model.mod_db_table;
            // 定义一个变量，用来存储标星文件的数量
            var perImgAccount = 0;
            if ($.isArray(dataset)) {
                $(dataset).each(function(k, paper) {
                    if (paper.insert_type != 'blank_page') {
                        window.fTitleOrder ++;
                    }
                    // 论文
                    var paper_jurnal = paper.jurnal;
                    var paper_jurnal_lever = paper.jurnal_lever;
                    // 专利
                    var patent_typeid = paper.typeid;
                    // 纵向课题
                    var govresearch_source = paper.source;
                    // 著作权
                    var software_copyright_type = paper.copyright_type;
                    // 个人获奖
                    var award_rank = paper.rank;
                    // 学生获奖
                    var stuaward_ranking = paper.ranking;
                    // 继续教育材料
                    var material_period = paper.period;
                    // 著作
                    var book_jurnal_type = paper.jurnal_type;
                    // 横向课题
                    var research_funds = paper.funds;
                    // 新闻报道
                    var report_media_name = paper.media_name;
                    // 把model放进paper数组里面去，方便存到dom上去
                    paper.modelTitle = model;
                    var title = paper.title;
                    //[标识]目录中的插入图片
                    var insertIndexId;
                    var caption = title;
                    if(paper.insert_type == 'img_page' || paper.insert_type == 'blank_page') {
                        var itemTitle = title;
                        insertIndexId = paper.index_id;
                    }
                    else{
                        if (paper.alt_title) {
                            var itemTitle = paper.alt_title;
                        } else {
                            switch(model) {
                            case 'paper':
                                if (paper_jurnal.indexOf('《') !== 0) {
                                    var itemTitle = '《' + paper_jurnal + '》' + title;
                                } else {
                                    var itemTitle = paper_jurnal + title;
                                }
                                if (paper_jurnal_lever) {
                                    var arr = paper_jurnal_lever.split(',');
                                    if (arr.length > 1) {
                                        $.each(arr, function() {
                                            itemTitle = itemTitle + ' [' + this +']';
                                        });
                                    } else {
                                        itemTitle = itemTitle + ' [' + paper_jurnal_lever +']';
                                    }
                                }
                                break;
                            case 'patent':
                                var itemTitle = '[' + patent_typeid + '] ' + title;
                                break;
                            case 'govresearch':
                                var itemTitle = '[' + govresearch_source +'] ' + title;
                                break;
                            case 'software':
                                var itemTitle = '[' + software_copyright_type + '] ' + title;
                                break;
                            case 'award':
                                var itemTitle = '[' + award_rank + '] ' + title;
                                break;
                            case 'stuaward':
                                var itemTitle = '[' + stuaward_ranking + '] ' + title;
                                break;
                            case 'material':
                                var itemTitle = '[' + material_period + '] ' + title;
                                break;
                            case 'book':
                                var itemTitle = '[' + book_jurnal_type + '] ' + title;
                                break;
                            case 'research':
                                var itemTitle = '[' + research_funds + '] ' + title;
                                break;
                            case 'report':
                                var itemTitle = '[' + report_media_name + '] ' + title;
                                break;
                            case 'certificate':
                                var itemTitle = title;
                                break;
                            default:
                                var itemTitle = title;
                            }
                            paper.alt_title = itemTitle;
                        }
                    }
                    var fileId = paper.doc_id;
                    var indexId = paper.index_id;
                    var modelTitle = paper.modelTitle;
                    var $itemTitleDom;

                    // 目录页：中的小标题(成果标题)
                    if(fileId || paper.show_in_catalog) {

                        $itemTitleDom = _this.createMenuDom(fileId, itemTitle, allPages.length, 'f-title', model, i, insertIndexId);

                        $menuPageContent.append($itemTitleDom);

                        // 在页面中已经不可见,得放入下一个页面
                        if (!that.inviewport($itemTitleDom.get(0), $menuPageContent)) {
                            menuPage  = _this.createPageDom(null, 'menuPage', 'render');
                            $('#hideArea').append(menuPage);
                            $menuPageContent =  $(menuPage).find('.content');
                            $menuPageContent.css({'width': contentWidth , 'height': contentHeight});
                            $menuPageContent.append($itemTitleDom);
                        }
                    }

                    if ($.isArray(paper._files)) {
                        var starFiles = [];
                        var length = paper._files.length || 1;
                        if (paper._files.length < 1 && paper.files_count == 0) {
                            page = _this.createNoAnnexDom(paper.fields, itemTitle, caption, length, 0, fileId, modelTitle);
                            allPages.push(page);
                        } else {
                            $(paper._files).each(function(index,item) {
                                if (item.star == 1) {
                                    starFiles.push(item);
                                }
                            });
                            if (settings && settings.just_starred) {
                                var files = starFiles;
                                paper.star_files = starFiles;
                            } else {
                                var files = paper._files;
                            }
                            $(files).each(function(j, img){
                                if (j == 0) {
                                    if (theme) {
                                        page = _this.createPageDom({img: img, title: itemTitle, caption: caption, length: length, index: j, indexId:indexId, fileId: fileId, model: modelTitle}, 'fileTitle', 'render');
                                    } else {
                                        page = _this.createPageDom({img: img, title: itemTitle, caption: caption, length: length, index: j, indexId:indexId, fileId: fileId, model: modelTitle}, 'fileTitle', null);
                                    }

                                    allPages.push(page);
                                } else {
                                    // 其他图片单独一页,加上页码
                                    // page = _this.createPageDom(img, 'img', allPages.length);
                                    if (theme) {
                                        page = _this.createPageDom({img: img, title: itemTitle, caption: caption, length: length, index: j, indexId, fileId: fileId, model: modelTitle}, 'fileTitle', 'render');
                                    } else {
                                        page = _this.createPageDom({img: img, title: itemTitle, caption: caption, length: length, index: j, fileId: fileId, model: modelTitle}, 'fileTitle', null);
                                    }
                                    allPages.push(page);
                                }
                            });
                        }
                    }
                });
                if (settings && settings.double_print) {
                    // 获取同一个大模块下面的所有文档的图片，如果图片总数是奇数，则最后加上一个空白页
                    var length = dataset.length;
                    var imgLength = 0;
                    for (var m=0; m<length; m++) {
                        if (settings && settings.just_starred) {
                            imgLength += (dataset[m].star_files ? dataset[m].star_files.length : 0);
                            delete dataset[m].star_files;
                        } else {
                            imgLength += dataset[m]._files.length;
                        }

                        if (m == length - 1) {
                            var docId = dataset[m].doc_id;
                            var docTitle = dataset[m].title;
                        }
                    }
                    if (imgLength % 2 !== 0) {
                        // 如果是奇数页，则最后追加一页空白页
                        var blankPage = $('<div>', {'class': 'blank-page page', 'data-fileid': docId, 'data-title': docTitle}).get(0);
                        allPages.push(blankPage);
                    }
                }
            }
        });

        // 添加页码
        $(allPages).each(function (i, page) {
        	$(page).find('span').text(i + 1);
            $(page).attr('data-index', i + 1);
        });

        this.renderFooterPage($(allPages), settings);

        this.renderPrintStyle($(allPages), settings);

        // 把目录分成两栏
        var menuDom = this.createMenuPage($('#hideArea').find('.page'), COL, settings);

        // 获取封面的dom
        if (theme) {
            var themeDom = this.pdfCover(theme);
            allPages = [themeDom,...menuDom, ...allPages];
        } else {
            allPages = [...menuDom];
        }

        this.randerAlignFont(menuDom, settings);

        $('#hideArea').remove();
        return allPages;
    },


    // 如果是单页面分享和下载   单个文件
    getPage: function(_files) {
        var allPages = [];
        var page = null; // 每个页面
        var _this = this;

        if ($.isArray(_files)) {
            $(_files).each(function(j, img){
                page = _this.createPageDom({img: img}, 'img', 'render');
                allPages.push(page);
            });
        }

        return allPages;
    },

    getNoAnnexPage: function (fields) {
        var page = this.createNoAnnexDom(fields);
        return page;
    },

    /**
     * 渲染无附件的默认图片
     */
    createNoAnnexDom: function (fields, title, caption, length, index, fileId, model) {
        if (fields && fields.length) {
            var $dom =  $('<div>',{'class':'page no-annex','data-title': title, 'data-caption': caption, 'data-length': length, 'data-subscript': index, 'data-fileid': fileId, 'data-model': model})
                        .append($('<div>',{'class': 'content'}));
            $dom.find('.content').append($('<div>', {'class': 'table-wrap'}));
            $dom.find('.table-wrap').append($('<table>', {'class': 'list', 'cellspacing': '10'}));
            fields.forEach((item, index) => {
                if (item.value) {
                    var $tr = $('<tr>',{'class':'list-item'})
                            .append($('<td class=title>' + item.text + ':</td>'))
                            .append($('<td class=value>' + item.value + '</td>'));
                    $dom.find('.list').append($tr);
                }
            });
            $dom.append($('<p>',{'class': 'file-title','text': title}));
            $dom.find('.file-title').append($('<span>',{'class': 'number','text': ''}));
            return $dom;
        }
    },

    /**
     * 把导航的页面分成多列
     * @param  {[array]} page      页面数据
     * @param  {[number]} colNumber 要分成多少列
     * @return {[type]}           返回拼接好的页面dom
     */
    createMenuPage: function (page, colNumber, settings) {
        var lines = page.length; // 数据来的时候分了的页面数
        var menuPages=[]; // 最终页面数据
        var col = []; // 页面内容抽取为单列

        if (lines > 0) {
            for(let i = 0; i < lines; i++ ) {
                col.push($('<div>', {class: 'col'}).append($(page[i]).find('.content')));
            }
        }

        // 页面数除以要分的列数 向上去整等于最后要生成的页面数
        var finalPages = Math.ceil(lines/colNumber); // 最终的页面数量

        var pageDom;
        var finalPage; // 最终单页面数据
        var className = '';
        if (settings) {
            if (settings.catalog_no) {
                className = 'template-' + parseInt(settings.catalog_no);
            } else {
                className = 'template-1';
            }
        } else {
            className = 'template-1';
        }
        for (let j = 0; j < finalPages; j++) {
            finalPage = $('<div>', {class: 'page menu ' + className});
            pageDom = col.slice(j*colNumber, colNumber*(j+1));

            $(pageDom).each(function (k, item) {
                finalPage = finalPage.append(item);
            });

            menuPages.push(finalPage);
        };

        return menuPages;
    },

    /**
     * 创建页面dom
     * @param  {[type]} data [description]
     * @param  {[string]} type
     * @return {[string]}      [description]
     */
    createPageDom: function (data, type, render) {
        var dom = '';

        if (render) {
            if (type === 'modelTitle'){
                dom =  $('<div>',{'class':'page'})
                        .append($('<div>',{'class': 'content'})
                        .append($('<h1>',{'class': 'model-title','text': data})));

            } else if (type === 'fileTitle') { // 文件的首页
                if (data.title == '空白页' || data.title == '无标题') {
                    dom =  $('<div>',{'class':'page', 'data-indexid': data.indexId, 'data-title': data.title, 'data-caption': data.caption, 'data-length': data.length, 'data-subscript': data.index, 'data-model': data.model})

                        .append($('<div>',{'class': 'content'})
                            .append($('<img>',{'src': data.img.url}))
                            .append($('<p>',{'class': 'file-title','text': data.title}))
                        );
                    $(dom).find('.file-title').append($('<span>',{'class': 'number','text': 'index'}));
                    dom = this.correctImg(data.img, dom);
                }else {

                    dom =  $('<div>',{'class':'page', 'data-indexid': data.indexId, 'data-fileid': data.fileId, 'data-title': data.title, 'data-caption': data.caption, 'data-length': data.length, 'data-subscript': data.index, 'data-model': data.model})

                        .append($('<div>',{'class': 'content'})
                            .append($('<img>',{'src': data.img.url}))
                            .append($('<p>',{'class': 'file-title','text': data.title}))
                        );
                    $(dom).find('.file-title').append($('<span>',{'class': 'number','text': 'index'}));
                    dom = this.correctImg(data.img, dom);
                }
            } else if (type === 'img') { // 文件页面(图片)
                dom =  $('<div>',{'class':'page', 'data-fileid': data.fileId, 'data-title': data.title, 'data-caption': data.caption, 'data-length': data.length, 'data-subscript': data.index, 'data-model': data.model})

                        .append($('<div>',{'class': 'content'})
                            .append($('<img>',{'src': data.img.url}))
                            .append($('<span>',{'class': 'number','text': ''}))
                        );
                dom = this.correctImg(data.img, dom);
            } else if (type === 'menuPage') {
                dom =  $('<div>',{'class':'page menu'})
                        .append($('<div>',{'class': 'content'}));
            }
        } else {
            dom =  $('<div>',{'class':'page menu'})
                    .append($('<div>',{'class': 'content'}));
        }
        return dom.get(0);
    },

    /**
     * 创建目录 DOM
     * @param  {string} fileId   [文档ID]
     * @param  {string} title    [渲染的alt_title]
     * @param  {number} index    [页码]
     * @param  {string} type     [大标题，小标题，目录]
     * @param  {string} category [模块类型]
     * @param  {int} i [大标题的下标]
     * @param  {int} insertIndexId [插入图片在数据中的索引id] [可不填，默认为null]
     * @return {DOM}          [创建好的DOM]
     */
    createMenuDom: function (fileId, title, index, type, category, i, insertIndexId = null) {
        if (type === 'm-title') {
            var $p = $('<p class="p-replace" data-type=' + category + '><span>' + title +'</span></p>');
            var $input = $('<input>', {'class': 'title', 'value': title, 'disabled': true});
            var $wrap = $p.append($input);

            var $order = $('<span class="order">' + (i+1) + '.</span>');

            var menuDom =  $('<div>',{'class': type})
                        .append($order)
                        .append($wrap);
        } else if (type === 'f-title') {
            // 得到最后一个字符
            title = $.trim(title);
            // 把空格替换成a占位符 因为span标签不认空格
            var spanTitle = title.replace(/\s\s/g,'a');
            var lastChar = title.substr(title.length - 1,1);
            var $textarea = $('<textarea class="title" disabled="disabled">' + title +'</textarea>');
            var $p = $('<p class="p-replace" data-index="' + (index + 1) + '"data-id="'+ (fileId?fileId:'') + '"data-insertIndexId="'+ (insertIndexId?insertIndexId:'') + '"data-type="' + category +'"><span>' + spanTitle +'<span class="last-char">' + lastChar + '</span></span></p>');
            var $wrap = $p.append($textarea);
            var $spanPseudoClass = $('<span class="span-pseudo-class"></span>');
            var $spanIndex = $('<span>', {'class': 'index', 'text': index + 1});

            var $order = $('<span class="order">' + (i+1) + '.' + (window.fTitleOrder+1) +'</span>');

            $spanIndex.append($spanPseudoClass);

            var menuDom =  $('<div>',{'class': type})
                        .append($order)
                        .append($wrap)
                        .append($spanIndex);
        } else if (type === 'catalog') {
            var menuDom =  $('<div>',{'class': type, 'text': title});
        }
        return menuDom;
    },

    /**
     * 根据封面排版数据返回封面的页面dom
     *
     * @param  {object} coverData [封面数据]
     * @return {dom}
     */
    generateCover: function(coverData) {
        var page = document.createElement('div');
        return page;
    },

    // 给PDF的封面 创建dom节点 把PDF封面的数据加载进去，第一个参数为数据，第二个参数为追加的节点
    pdfCover: function (pdfdata) {
        var $page = $('<div>', {'class':'page','id':'theme'});
        var cover = document.createElement('div');
        $page.append(cover);
        $('body').append($page);
        cover.setAttribute('class','pdf-cover');
        // 这里给cover的宽度和高度和page是一样的
        if($('#content').hasClass('mobile')) {
            PAGEWIDTH = 595.28;
            OFFSETLEFT = 24;
            OFFSETRIGHT = 24;
            OFFSETTOP = 36;
            OFFSETBOTTOM = 36;
            var contentHeight = PAGEWIDTH/RATIO;
            $(cover).css({'width':PAGEWIDTH + 'px','height': contentHeight + 'px', 'position':'relative'});
        } else {
            $(cover).css({'width': PAGEWIDTH + 'px','height':PAGEWIDTH/RATIO + 'px','position':'relative'});
        }
        if(pdfdata) {
            var coverHeight = $(cover).outerHeight();
            var datatype,datatype1,top,text,key,value,len,max,arr=[];
            var listitem = document.createElement('div');
            listitem.className = 'drag list-item';
            $(cover).append($(listitem));

            for (let i=0,l=pdfdata.length;i<l;i++) {
                datatype = pdfdata[i].type;
                datatype1 = pdfdata[i].type;
                var drag = document.createElement('div');
                var inputEle = document.createElement('input');
                inputEle.setAttribute('disabled','true');
                drag.className = 'drag';
                top = pdfdata[i].top * coverHeight;
                $(drag).css({'top':top});
                if (pdfdata[i].font) {
                    if (pdfdata[i].font === '宋体') {
                        $(drag).css({'font-family': 'Songti SC,"宋体",serif'});
                    } else {
                        $(drag).css({'font-family': 'Heiti SC,"微软雅黑","华文细黑",Droid Sans Fallback,sans-serif'});
                    }
                } else {
                    $(drag).css({'font-family': 'Heiti SC,"微软雅黑","华文细黑",Droid Sans Fallback,sans-serif'});
                }
                switch (datatype)
                {
                case 'h1':
                case 'h2':
                case 'h3':
                case 'word':
                case 'time':
                    text = pdfdata[i].value.text;
                    $(inputEle).val(text);
                    $(drag).append($(inputEle));
                    $(cover).append($(drag));
                    switch (datatype1)
                    {
                    case 'h1':
                        inputEle.className = 'h1';
                        break;
                    case 'h2':
                        inputEle.className = 'h2';
                        break;
                    case 'h3':
                        inputEle.className = 'h3';
                        break;
                    case 'word':
                        inputEle.className = 'word';
                        break;
                    }
                    break;
                case 'item':
                    $(listitem).css({'top':top});
                    var drag = document.createElement('div');
                    drag.setAttribute('data-type','item');
                    if (pdfdata[i].font) {
                        if (pdfdata[i].font === '宋体') {
                            $(drag).css({'font-family': 'Songti SC,"宋体",serif'});
                        } else {
                            $(drag).css({'font-family': 'Heiti SC,"微软雅黑","华文细黑",Droid Sans Fallback,sans-serif'});
                        }
                    } else {
                        $(drag).css({'font-family': 'Heiti SC,"微软雅黑","华文细黑",Droid Sans Fallback,sans-serif'});
                    }
                    var inputEleList = document.createElement('input');
                    inputEleList.setAttribute('disabled','true');
                    inputEleList.className= 'list';
                    var nodeText = document.createTextNode(' ：');
                    var inputEleUn = document.createElement('input');
                    inputEleUn.setAttribute('disabled','true');
                    inputEleUn.className = 'underline';
                    $(drag).append($(inputEleList));
                    $(drag).append($(nodeText));
                    $(drag).append($(inputEleUn));
                    $(listitem).append($(drag));
                    key = pdfdata[i].value.key;
                    value = pdfdata[i].value.value;
                    $(inputEleList).val(key);
                    $(inputEleUn).val(value);
                    len = this.calcInputWidth(inputEleList);
                    arr.push(len);
                    break;
                case 'image':
                    var imageEle = document.createElement('img');
                    imageEle.src = pdfdata[i].value.url;
                    imageEle.id = 'school_emblem';
                    $(drag).append($(imageEle));
                    $(cover).append($(drag));
                    break;
                }
            }
            max = Math.max.apply(null, arr);
            // 设置 条目项 中标题input元素的宽度
            $('.pdf-cover [data-type="item"]').find('.list').width(max);
        }
        this.indentListItems();
        this.eachJustifyInput();
        // 临时dom从页面中删除
        $page.removeAttr('id');
        this.replaceInput();
        $page.remove();
        return $page.get(0);
    },

    // 获取需要两端对齐的input 替换成span标签 下载PDF的时候显示封面用 因为PDF里面的input不支持letter-spacing
    replaceInput: function() {
        $('input.list').each(function () {
            // 获取input的样式并赋给span元素
            var height = $(this).css('height');
            var width = $(this).css('width');
            var letterSpacing = $(this).css('letter-spacing');
            var fontFamily = $(this).css('font-family');
            var fontSize = $(this).css('font-size');
            if ($('#content').hasClass('mobile')) {
                fontSize = 12;
            }
            var value = $(this).val();
            var spanEle = $('<span>',{text:value,class:'list'}).css({
                'display': 'inline-block',
                'white-space': 'nowrap',
                'width': width,
                'height': height,
                'line-height': height,
                'font-family': fontFamily,
                'font-size': fontSize,
                'letter-spacing':letterSpacing
            });
            $(this).replaceWith(spanEle[0]);
        });
    },

    // 对齐list项目
    indentListItems: function() {
        const that = this;
        const $listitems = $('#theme .pdf-cover .list-item').find('[data-type="item"]');
        let maxWidth = 0, itemWidth = 0;
        let maxValueWidth = 0, itemValueWidth = 0;
        $listitems.each(function(i, item) {
            itemWidth = that.calcInputWidth($(this).find('input')[0]);
            itemValueWidth = that.calcInputWidth($(this).find('input')[1]);

            if (itemWidth > maxWidth) {
                maxWidth = itemWidth;
            }

            if (itemValueWidth > maxValueWidth) {
                maxValueWidth = itemValueWidth;
            }
        });

        if (maxWidth) {
            $listitems.find('.list').width(maxWidth);
        }

        if (maxValueWidth) {
            const minWidth = parseInt($('.pdf-cover').width() * 0.35, 10);
            maxValueWidth = Math.max(maxValueWidth, minWidth);
            $listitems.find('.underline').width(maxValueWidth);
        }
    },

    calcInputWidth: function(input){
        if ($('#content').hasClass('mobile')) {
            $(input).css({'font-size': MOBILEFONTSIZE});
        }
        var fontFamily = $(input).css('font-family');

        const len = TextUtil.length(input.value);

        const $clone = $(input).clone();

        $clone.val(input.value);
        $clone.css({
            'z-index':-100000000,
            'pointer-events': 'none',
            'visibility': 'hidden',
            'position': 'absolute',
            'width': 'auto',
            'height': '20px',
            'letter-spacing': 0,
            'font-family': fontFamily,
        });
        $clone.attr('size', len);

        $(input).before($clone);

        let width = $clone.width();
        $clone.remove();
        return width;
    },

    // 让input框两端对齐 input框失焦 和 渲染数据的时候调这个函数
    justifyInputText: function(input) {
        var inputWidth = $(input).width();  //需要两端对齐的input的宽度
        var length = $(input).val().length; //input框总共有多少个字
        var aWord = this.calcTextWidthInInput(input); //得到一个字的宽度
        var freeWidth = inputWidth - length * aWord;
        var letterSpacing = freeWidth/(length-1);
        $(input).css({'letter-spacing':letterSpacing + 'px'});
    },

    // 遍历需要两端对齐的input框，并让他们两端对齐
    eachJustifyInput: function () {
        var _this = this;
        $('#theme .pdf-cover .list').each(function(){
            if ($('#content').hasClass('mobile')) {
                $(this).css({'font-size':MOBILEFONTSIZE});
            }
            _this.justifyInputText(this);
        });
    },

    /**
     * 得到input中的字的宽度
     *
     * @return {[type]} [description]
     */
    calcTextWidthInInput: function(input){
        const $clone = $(input).clone();
        const fontSize = $(input).css('font-size');
        $clone.val(input.value);
        $clone.css({
            'z-index':-100000000,
            'pointer-events': 'none',
            'visibility': 'hidden',
            'position': 'absolute',
            'width': 'auto',
            'font-size': fontSize
        });

        $(input).before($clone);

        $clone.val('中文');

        var $text = $clone.text();
        if($text=='') $text = $clone.val();
        var $div = $('<div>',{
            style: 'clear:both;display:block;visibility:hidden;'
        }).append(
            $('<span>',{
                text: $text
            }).css({
                'width':'inherit',
                'margin':'0',
                'font-family': $clone.css('font-family'),
                'font-size': $clone.css('font-size'),
                'font-weight':  $clone.css('font-weight')
            })
        );

        $('body').append($div);
        var width = $('body').find('span:last').width() / $clone.val().length;
        $('body').find('span:last').parent().remove();

        $clone.remove();
        return width;
    }

};

